package com.beemans.corekit.integration.polling;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import androidx.work.ExistingWorkPolicy;
import androidx.work.OneTimeWorkRequest;
import androidx.work.WorkManager;

import java.util.Objects;
import java.util.concurrent.atomic.AtomicLong;

public class ScreenOnReceiver extends BroadcastReceiver {
    private static final String TAG = ScreenOnReceiver.class.getSimpleName();

    // 上一次检索时间戳
    private static final AtomicLong lastCheckInterval = new AtomicLong(0);

    @Override
    public void onReceive(Context context, Intent intent) {
        final String action = intent != null ? intent.getAction() : null;
        if (!Objects.equals(action, Intent.ACTION_USER_PRESENT)) {
            return;
        }

        final long now = System.currentTimeMillis();
        final long last = lastCheckInterval.get();
        if (Math.abs(now - last) < 2000) {
            return;
        }

        lastCheckInterval.set(now);

        final String uniqueWorkName = TAG + ExistingWorkPolicy.REPLACE.name();
        final OneTimeWorkRequest oneTimeRequest = new OneTimeWorkRequest.Builder(UserPresentWorker.class)
                .build();
        WorkManager.getInstance(context)
                .enqueueUniqueWork(uniqueWorkName, ExistingWorkPolicy.REPLACE, oneTimeRequest);
    }
}